import { reqLogin, reqLogout } from '@/api/user'

const initState = JSON.parse(localStorage.getItem('userInfo')) || {
  name: '',
  token: '',
}

export default {
  namespaced: true,
  state: initState,
  actions: {
    async login({ commit }, { phone, password }) {
      const res = await reqLogin({ phone, password })
      commit('LOGIN', res)
    },
    async logout({ commit }) {
      await reqLogout()
      commit('LOGOUT')
    },
  },
  mutations: {
    LOGIN(state, res) {
      state.name = res.name
      state.token = res.token
      const userInfo = { token: res.token, name: res.name }
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
    },
    LOGOUT(state) {
      state.name = ''
      state.token = ''
      localStorage.removeItem('userInfo')
    },
  },
}
